
//
//  BBHomeViewController.m
//  BlockBrowser
//
//  Created by Mac on 2018/3/28.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "BBHomeViewController.h"
#import "BBPhoneLoginViewController.h"
#import "KLClearTableHeaderView.h"
#import "BBHomeHeaderView.h"
#import "BBArticleViewController.h"
#import "BBArticleViewController.h"
#import "BBHomeTableViewCell.h"
#import "BBLoginHomeViewController.h"
#import "BBLoginHomeViewController.h"
#import "BBHomeMenuModel.h"
#import "BBArticleModel.h"
#import "BBHomeWebTableViewCell.h"
#import "NSCalendar+STCalendarTool.h"
#import "BBHomeMenuPresentViewController.h"
#import "BBMineViewController.h"
#import "BBGlobalSearchViewController.h"
#import "STLocationManger.h"
#import "BBShareNewsPresentViewController.h"
#import "TMTabbarViewController.h"
@interface BBHomeViewController ()<BBHomeHeaderViewDelegate>
@property(nonatomic, strong) BBHomeHeaderView                     *header;
@property(nonatomic, strong) KLClearTableHeaderView                     *clearTableheader;
@property(nonatomic, assign) BOOL                     canPush;

@property(nonatomic, strong) BBUserModel                     *userModel;
@property(nonatomic, strong) NSMutableArray <BBHomeMenuModel*>                    *menuArray;
@property(nonatomic, strong) NSMutableArray                     *dataSouce;
@end

@implementation BBHomeViewController
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
#pragma mark --vc 生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    [self sendGetReadAward];
    [BBArticleViewController defult];
    [self configSubView];
    [self sendHomeMenuListRequest];
    [self sendHomeArtistListRequest];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [[BBNavHistoryManger manger] autoJudgeAddViewController:self];
    
    [[STLocationManger defult] startUpdatingLocationHande:^(STError *error, CLPlacemark *placemark) {
        if (placemark) {
            [[STLocationManger defult] updatePlacemarkWith:placemark];
            
            [self sendWhereRequestWithCity:[STLocationManger defult].lastCity];
        }
    }];
   
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //  [self scrollViewDidScroll:self.tableView];
    //   [self.tableView setContentOffset:CGPointZero animated:YES];
    self.canPush = YES;
    [self st_hideNavagetionbarAnimated:animated];
    [self findUser];
    [self sendHomeArtistListRequest];
    [self sendHomeMenuListRequest];
    [self sendWhereRequestWithCity:[STLocationManger defult].lastCity];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self showBackAnimation];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        BOOL openLast = [[NSUserDefaults standardUserDefaults] boolForKey:openLastKey];
        BOOL diedIsAtHome = [[NSUserDefaults standardUserDefaults] boolForKey:diedIsAtHomeKey];
        if (openLast && !diedIsAtHome) {
            BBScanHistoryModel * model  = [[BBHistoryManger manger] scanArray].lastObject;
            STWebViewController * webvc =  [[STWebViewController alloc] initWithUrl:model.url];
            webvc.forceTitle = model.title;
            webvc.shouldNotRecord = YES;
            [self.navigationController pushViewController:webvc animated:YES];
        }
        
    });
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:diedIsAtHomeKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self st_showNavagationbarAnimated:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)findUser{
    [TMUtils sendUserInfoRequest:^(BBUserModel *user) {
        self.userModel = user;
        self.header.searchView.userModel = user;
        if (!user) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                static dispatch_once_t onceToken;
                dispatch_once(&onceToken, ^{
                    [self findUser];
                });
            });
            
        }
    }];
}
#pragma mark --subView
- (void)configSubView{
    self.view.backgroundColor = [UIColor whiteColor];
    self.header = [[BBHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, homeHeaderViewHeight)];
    self.header.delegate = self;
    self.header.weakTableView = self.tableView;
    self.header.weakhomeVC = self;
    [self.view insertSubview:self.header atIndex:0];
    
    self.clearTableheader = [[KLClearTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, self.header.height)];
    self.clearTableheader.backgroundColor = [UIColor clearColor];
    self.clearTableheader.hitTestView = self.header;
    self.tableView.tableHeaderView = self.clearTableheader;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    
    CGFloat tabbarTop;
    if (KIsiPhoneX) {
        tabbarTop = UIScreenHeight - 83;
    }else{
        tabbarTop = UIScreenHeight - 49;
    }
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 0, (UIScreenHeight -tabbarTop),0);
    self.tableView.contentInset = inset;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1    ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [BBHomeTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //  return 0.01;
    return 53;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 53)];
    header.backgroundColor = TM_backgroundColor;
    NSString * week = [NSCalendar st_todayWeekDay];
    NSString * title = [NSString stringWithFormat:@"今天%@   %@",[NSDate st_localCurrentDate].st_yyyyMMddhhmmssWithDate,week];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 0, UIScreenWidth - 30, 53)
                                                     text:title
                                                textColor:SecendTextColor
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [header addSubview:titleLable];
    return header;
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    BBHomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[BBHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.model = self.dataSouce[indexPath.row];
    __weak typeof(self) weakSelf =  self;
    [cell.shareButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedShareButtonWithIndexPath:indexPath];
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BBArticleModel*model = self.dataSouce[indexPath.row];
    STWebViewController * vc =   [[STWebViewController alloc] initWithH5String:model.content];
    vc.forceTitle = @"文章详情";
    vc.shouldNotRecord = YES;
    vc.progressBackgroundColor = FlatGray;
    vc.progressTintColor = FlatMint;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.willShowResetAnimation) {
        return;
    }
    if (scrollView == self.tableView) {
        NSLog(@"首页滑动 %0.2f",self.tableView.contentOffset.y);
        CGFloat scrollY = scrollView.contentOffset.y;
        CGFloat maxy = self.header.height - 64;
        if (scrollY >= maxy) {
            [self.tableView setContentOffset:CGPointMake(0, maxy) animated:NO];
            
            //弹出控制器
            if (self.canPush) {
                static dispatch_once_t onceToken;
                dispatch_once(&onceToken, ^{
                    [SVProgressHUD showWithStatus:@"刷新中"];
                });
                BBArticleViewController * vc = [BBArticleViewController defult];
                vc.page = 1;
                [vc.tableView.mj_footer endRefreshing];
                [self.navigationController pushViewController:vc animated:NO];
                [self.tableView setContentOffset:CGPointMake(0, maxy - 2) animated:NO];
                self.canPush = NO;
                self.willShowResetAnimation = YES;
                self.header.canShowRefreshAnimation = NO;
            }
            
            
            
        }
        [self.header scrollviewDidScroll:self.tableView];
    }
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self.header scrollViewDidEndScrollingAnimation:scrollView];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self.header scrollViewDidEndDecelerating:scrollView];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    CGFloat scrollY = scrollView.contentOffset.y;
    [self.header scrollViewDidEndDragging:scrollView];
    return;
    if (scrollY > self.header.height * 0.2 ) {
        [UIView animateWithDuration:0.25 animations:^{
            [self.tableView setContentOffset:CGPointMake(0, self.header.height - 64) animated:NO];
        } completion:^(BOOL finished) {
            
        }];
        
    }
}



#pragma mark --BBHomeHeaderViewDelegate
- (void)homeHeaderVewSelctedSearchWithTitle:(NSString*)title{
    if ([title isEqualToString:@"用户"]) {
        if (self.userModel) {
            [self gotoMineViewController];
        }else{
            [self.navigationController pushViewController:[BBPhoneLoginViewController new] animated:YES];
        }
    }
    if ([title isEqualToString:@"搜索"]) {
        BBGlobalSearchViewController * vc = [BBGlobalSearchViewController new];
        [vc setDidSelctedSearch:^(NSString *keyword) {
            [self onSelctedSearchWithKeyWord:keyword];
        }];
        STNavigationController * nav = [[STNavigationController alloc] initWithRootViewController:vc];
        
        [self presentViewController:nav animated:YES completion:nil];
    }
    
}
- (void)homeHeaderVewSelctedMenuWithTitle:(NSString*)title{
    BBHomeMenuModel * model  = [self modelFormDataSouceWithTitle:title];
    if (model) {
        if ([model.name isEqualToString:@"挖矿"]) {
            [self gotoMineViewController];
        }else{
            STWebViewController * vc =   [[STWebViewController alloc] initWithUrl:model.url];
            vc.forceTitle = title;
            vc.progressBackgroundColor = FlatGray;
            vc.progressTintColor = FlatMint;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
        
    }
    
}
- (BBHomeMenuModel*)modelFormDataSouceWithTitle:(NSString*)title{
    for (BBHomeMenuModel * model in self.menuArray) {
        if ([model.name isEqualToString:title]) {
            return model;
        }
    }
    return nil;
}
#pragma mark --Private Method
- (void)gotoMineViewController{
    BBMineViewController * vc = [BBMineViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --NetWork Method
- (void)sendHomeMenuListRequest{
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/advert/list"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSArray * array = responseObject[@"data"];
                                                 self.menuArray = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in array) {
                                                     BBHomeMenuModel * model = [BBHomeMenuModel mj_objectWithKeyValues:modelDic];
                                                     [self.menuArray addObject:model];
                                                 }
                                                 self.header.menuView.dataSouce = self.menuArray;
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendHomeArtistListRequest{
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/news/list"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSArray * array = responseObject[@"data"][@"list"];
                                                 self.dataSouce = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in array) {
                                                     BBArticleModel * model = [BBArticleModel mj_objectWithKeyValues:modelDic];
                                                     [self.dataSouce addObject:model];
                                                 }
                                                 [self.tableView reloadData];
                                                 BBArticleViewController * vc = [BBArticleViewController defult];
                                                 vc.view.backgroundColor =  vc.view.backgroundColor;
                                                 vc.dataSouce = self.dataSouce;
                                                 [vc.view setNeedsDisplay];
                                                 [vc.view layoutIfNeeded];
                                                 [vc.view setNeedsLayout];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)showBackAnimation{
    if (self.willShowResetAnimation) {
        [UIView animateWithDuration:0.25 animations:^{
            [self.tableView setContentOffset:CGPointZero animated:NO];
            [self.header menuViewAnimationWithScrollView:self.tableView];
            [self.header searchBootomAnimationWithScrollView:self.tableView];
            [self.header scrollviewDidScroll:self.tableView];
        } completion:^(BOOL finished) {
            self.willShowResetAnimation = NO;
        }];
    }
    
}
#pragma mark --Action Method
- (void)onSelctedSearchWithKeyWord:(NSString*)keyword{
    //    search    "https://www.baidu.com/s?wd="
    //    suggestion    "http://suggestion.baidu.com/su?wd="
    NSString * finsh = [keyword stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * url = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",finsh];
    NSURL * keywordurl =   [NSURL URLWithString:keyword];
    BOOL isUrl =  [keywordurl checkResourceIsReachableAndReturnError:nil];
    if (isUrl) {
        url = keywordurl.description;
    }
    STWebViewController * vc =   [[STWebViewController alloc] initWithUrl:url];
    vc.forceTitle = keyword;
    vc.progressBackgroundColor = FlatGray;
    vc.progressTintColor = FlatMint;
    [self.navigationController pushViewController:vc animated:YES];
    //   [[BBNavHistoryManger manger] autoJudgeAddViewController:vc];
}
- (void)onSelctedShareButtonWithIndexPath:(NSIndexPath*)indexPath{
    BBArticleModel *  model = self.dataSouce[indexPath.row];
    BBHomeTableViewCell * cell = [(id)self.tableView cellForRowAtIndexPath:indexPath];
    BBShareNewsPresentViewController * vc = [BBShareNewsPresentViewController new];
    vc.time = model.dateline;
    vc.news = cell.contenLable.text;
    [vc setShareButtonHandle:^(NSString *title, UIImage *shareImage) {
        TMTabbarViewController * tabvc = (id)[UIApplication sharedApplication].keyWindow.rootViewController;
        [tabvc shareWithChosedTitle:title image:shareImage];
    }];;
    [self presentViewController:vc animated:NO completion:nil];
}
#pragma mark --NetWork Method
- (void)sendWhereRequestWithCity:(NSString*)city{
    if (!city.length) {
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    NSString * newUrl = @"http://v.juhe.cn/weather/index";
    NSMutableDictionary * parameters  = [NSMutableDictionary new];
    [parameters setObject:@"6a573accfa39494ccde3cdd8ce24a487" forKey:@"key"];
    [parameters setObject:city forKey:@"cityname"];
    [manager GET:newUrl parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSInteger code = [responseObject[@"resultcode"] integerValue];
        if (code == 200) {
            NSDictionary * result = responseObject[@"result"];
            BBWheatherModel * model = [BBWheatherModel new];
            model.temp = result[@"sk"][@"temp"];
            model.city = city;
            model.weather = result[@"today"][@"weather"];
            model.fb = result[@"today"][@"weather_id"][@"fb"];
            if (model.fb.integerValue < 30) {
                model.desFb = @"优";
            }else if (model.fb.integerValue < 60){
                model.desFb = @"良";
            }else{
                model.desFb = @"污染";
            }
            self.header.searchView.weather = model;
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)sendGetReadAward{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",severHeader,@"/api/user/readAward"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 

                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {

                                             }];
}
@end

